﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Transactions;
using Budgeteer.Services.Common;
using Budgeteer.Services.DataProviders;
using Budgeteer.Services.Domain;

namespace Budgeteer.Services
{
    public class ChargeService
    {
        static readonly Regex TransactionLine = new Regex(
            @"""?(?<Time>\d{1,2}/\d{1,2}/\d{4})""?,?""?(?<Name>.+)""?,(?<Amount>[\d\.\-]+)",
            RegexOptions.Compiled);
        
        readonly ChargeDataProvider chargeDataProvider;
        readonly ConfigService config;

        public ChargeService(ChargeDataProvider chargeDataProvider, ConfigService config)
        {
            this.chargeDataProvider = chargeDataProvider;
            this.config = config;
        }

        public virtual IList<ChargeDto> ParseTransactionFiles(string dataFolder,Func<string,string> getChargeCategory)
        {
            IList<ChargeDto> ret = new List<ChargeDto>();

            foreach(string path in Directory.GetFiles(dataFolder,"*.csv",SearchOption.TopDirectoryOnly))
            {
                using(StreamReader file = File.OpenText(path))
                {
                    while(!file.EndOfStream)
                    {
                        string line = file.ReadLine();

                        ChargeDto t = new ChargeDto();

                        Match m = TransactionLine.Match(line);

                        t.Time = Convert.ToDateTime(m.Groups["Time"].Value);
                        t.Name = m.Groups["Name"].Value;
                        t.Amount = Convert.ToDecimal(m.Groups["Amount"].Value);
                        t.Category = getChargeCategory(t.Name);
                        t.Account = "Visa";

                        ret.Add(t);
                    }
                }
            }

            return ret;
        }

        public virtual void ImportTransactionData(Func<string,string> getChargeCategory)
        {
            string dataFolder = config.GetString("TestDataFolder");

            IList<ChargeDto> transactions = ParseTransactionFiles(dataFolder,getChargeCategory);

            using(TransactionScope ts = BaseDataProvider.CreateTransactionScope())
            {
                foreach (ChargeDto transaction in transactions)
                {
                    chargeDataProvider.InsertTransactionData(transaction);
                }

                ts.Complete();
            }
        }
    }
}
